//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    assets:app.config.assets,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    wx.showShareMenu({
      complete: (res) => {},
    })
    this.getData();
  },

  getData:function(){
    var context = this;
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    wx.request({
      url: app.config.server + '/api/banners',
      success:res => {
        context.setData({
          images:res.data
        })
      }
    })
    wx.request({
      url: app.config.server + '/api/hots',
      success:res => {
        context.setData({
          hots:res.data
        })
      }
    })
    
    wx.request({
      url: app.config.server + '/api/newcourses',
      success:res => {
        context.setData({
          newcourses:res.data
        })
      }
    })
  },
  onShareAppMessage: function () {
    return {
      title: "智原学-华信智原专业的IT技术人才培养企业",
      desc: "你想学的IT课程这里都有!",
      path: '/pages/index/index?share_openid=' + wx.getStorageSync('openid')
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo;
    wx.request({
      url:app.config.server + "/api/register",
      method:'POST',
      header:{
        sessionkey:wx.getStorageSync('session_key')
      },
      data:e.detail.userInfo,
      success: res => {
        console.log(res);
      }
    })
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: e.detail.userInfo.nickName != undefined
    })
  },
  redirect:function(e){
    wx.redirectTo({
      url: e.currentTarget.dataset.url,
    })
  },
  navigate:function(e){
    wx.navigateTo({
      url: e.currentTarget.dataset.url,
    })
  },
  contact:function(e){
    console.log(e);
  }
})
